<style scoped lang="scss">
.edit-user {
  width: 10rem;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  background-color: #161622;

  .edit-user-header {
    width: 10rem;
    height: 1.12rem;
    @include flex-center;
    font-size: .4267rem;
    color: $color-white;
    border-bottom: 0.5px solid rgba(41, 40, 37, 0.8);

    ul {
      width: 9rem;
      margin: 0 auto;
      height: 1.12rem;
      @include flex-space-between-center;
    }
  }

  .edit-user-avatar {
    width: 10rem;
    height: 4.6667rem;
    @include flex-center;
    flex-direction: column;
    font-size: .4267rem;
    color: $color-white;
    position: relative;
    margin-bottom: .5333rem;

    .edit-user-avatar-img {
      width: 2.6667rem;
      height: 2.6667rem;
      border-radius: 50%;
      border: 1px solid $color-white;

      img {
        width: 2.6667rem;
        height: 2.6667rem;
        border-radius: 50%;
      }
    }

    p {
      margin-top: .2667rem;
      color: #8b8c96;
      font-size: .32rem;
    }

    input {
      width: 2.6667rem;
      height: 3.7333rem;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      left: 50%;
      transform: translate(-50%, -50%);
      opacity: 0;
    }

  }

  .edit-user-item {
    width: 9rem;
    margin: 0 auto;
    height: 1.7067rem;
    color: $color-white;
    position: relative;
    @include flex-space-between-center;

    p {
      font-size: .4267rem;
    }

    input,
    select {
      width: 5.3333rem;
      height: 1.1733rem;
      border: none;
      background-color: transparent;
      text-align: right;
      color: $color-white;
      font-size: .4267rem;
      outline: none;
      appearance: none;
    }

    select option {
      background-color: #161622;
      color: $color-white;
    }
  }
}

@keyframes edit-user-fade-in {
  from {
    opacity: 0;
    transform: translateX(100%);
  }

  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.edit-user-enter-active {
  animation: edit-user-fade-in 0.3s ease-in-out;
}

@keyframes edit-user-fade-out {
  from {
    opacity: 1;
    transform: translateX(0);
  }

  to {
    opacity: 0;
    transform: translateX(100%);
  }
}

.edit-user-leave-active {
  animation: edit-user-fade-out 0.3s ease-in-out;
}

.gender-select-vertical {
  display: flex;
  gap: 0.2667rem;
  /* 两个盒子间距 */
  width: 2.2rem;
  /* 和原有input宽度一致 */
  align-items: flex-end;
  /* 右对齐，和其他表单项统一 */
}

.gender-box {
  width: 1rem;
  /* 宽度占满容器 */
  height: 1rem;
  /* 和原有input高度一致 */
  @include flex-center;
  font-size: 0.4267rem;
  color: #8b8c96;
  border: 1px solid #333344;
  border-radius: 0.08rem;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    border-color: #8b8c96;
    color: $color-white;
  }
}

.gender-box.selected {
  border-color: $color-white;
  color: $color-white;
  background-color: rgba(255, 255, 255, 0.08);
}
</style>
<template>
  <Transition name="edit-user">
    <teleport to="body">
      <div class="edit-userbox">
        <div class="edit-user" v-if="isShow">
          <div class="edit-user-header">
            <ul>
              <!-- 通知父组件关闭弹窗 -->
              <li><i class="iconfont icon-fanhui" @click="closeModal"></i></li>
              <li>
                编辑个人资料
              </li>
              <li></li>
            </ul>
          </div>
          <!-- 点击更换头像区域 -->
          <div class="edit-user-avatar">
            <div class="edit-user-avatar-img">
              <img :src="'http://43.138.15.137:3000' + userInfo.userAvatar" alt="" ref="avatarImg">
            </div>
            <p>点击更换头像</p>
            <!-- 点击更换头像后，触发图片裁剪器 -->
            <input type="file" accept="image/*" @change="handleAvatarChange" />
          </div>
          <div class="edit-user-item">
            <p>昵称</p>
            <input type="text" v-model="userInfo.userNickname" placeholder="请输入用户名" />
          </div>
          <div class="edit-user-item">
            <p>签名</p>
            <input type="text" v-model="userInfo.userDesc" placeholder="请设置个性签名" />
          </div>
          <div class="edit-user-item">
            <p>性别</p>
            <div class="gender-select-vertical">
              <div class="gender-box" :class="{ selected: userInfo.userGender === '男' }"
                @click="userInfo.userGender = '男'">
                男
              </div>
              <div class="gender-box" :class="{ selected: userInfo.userGender === '女' }"
                @click="userInfo.userGender = '女'">
                女
              </div>
            </div>
          </div>
          <div class="edit-user-item">
            <p>年龄</p>
            <input type="text" v-model="userInfo.userAge" placeholder="21" style="width: 1.6rem;" />
          </div>
          <div class="edit-user-item">
            <p>地区</p>
            <input type="text" v-model="userInfo.userAddress" placeholder="请输入地区" @click="areaPickerVisible = true" />
          </div>
          <div class="edit-user-item">
            <AvatarUploader :isShow="isAvatarUploaderShow" />
          </div>
        </div>
        <div class="imgecropper">
          <ImageCropper :isShow.sync="isImageCropperShow" :imageUrl="avatarPreviewUrl" @close="handleClose"
            @confirm="handleConfirm" />
        </div>
        <div class="areapicker">
          <AreaPicker v-model:showDefault="areaPickerVisible" v-model:selectedAreaProvince="selectedProvince"
            v-model:selectedAreaCity="selectedCity" v-model:selectedAreaDistrict="selectedDistrict" />
        </div>
      </div>
    </teleport>
  </Transition>
</template>
<script setup>
import { modifyUserInfoAPI, uploadAvatarAPI } from '@/api/user/user'
import { isObjectEqual } from '@/utils/objectUtils'
import AvatarUploader from './AvatarUploader.vue';
import ImageCropper from './ImageCropper.vue';
import AreaPicker from './AreaPicker.vue';
import { ref, watch, onMounted, getCurrentInstance } from 'vue';
const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({})
  },
  isShow: {
    type: Boolean,
    default: false
  }
})
// 地区选择器
const areaPickerVisible = ref(false)
const selectedProvince = ref('')
const selectedCity = ref('')
const selectedDistrict = ref('')
const selectedArea = ref({
  province: '',
  city: '',
  district: ''
})
// 截取地区字符串方法
// 将地址字符串解析为省市区对象
function parseAddress(address) {
  console.log(address);

  if (!address) return;
  const addressParts = address.split('/');
  if (addressParts.length >= 3) {
    selectedArea.value = {
      province: addressParts[0],
      city: addressParts[1],
      district: addressParts[2]
    };
    // 同时设置单独的变量
    selectedProvince.value = addressParts[0];
    selectedCity.value = addressParts[1];
    selectedDistrict.value = addressParts[2];
  }
  console.log(selectedArea.value);
}

watch(props.userInfo, (newVal) => {
  parseAddress(props.userInfo.userAddress);
  userInfo.value = { ...newVal }
});

// 监听地区选择器的变化，同步到用户信息
watch([selectedProvince, selectedCity, selectedDistrict], ([province, city, district]) => {
  if (province && city && district) {
    userInfo.value.userAddress = `${province}/${city}/${district}`;
  }
});

onMounted(() => {
  parseAddress(props.userInfo.userAddress);
  console.log(userInfo.value);
});

const instance = getCurrentInstance();
const proxy = instance ? instance.proxy : null;
let isAvatarUploaderShow = ref(false);
const emit = defineEmits(['close'])
const avatarImg = ref(null);
// 复制userInfo
const userInfo = ref({ ...props.userInfo })
watch(
  () => props.userInfo,
  (newVal) => {
    userInfo.value = { ...newVal }; // 深拷贝，确保响应式
    parseAddress(newVal.userAddress); // 同步地区解析
  },
  { deep: true, immediate: true } // immediate: 首次加载就执行；deep: 监听对象内部变化
);

// 关闭弹窗
async function closeModal() {
  // 检查是否有修改
  const hasChanged = !isObjectEqual(userInfo.value, props.userInfo);

  if (!hasChanged && !avatarCroppedUrl.value) {
    emit('close')
    return
  }
  try {
    // 等待用户确认（确认时 resolve，取消时 reject）
    await proxy.$confirm({
      title: '确认修改',
      content: '是否确认修改个人信息？'
    });

    // 上传头像
    await uploadAvatar();
    // 用户点击“确认”：执行修改
    await modifyUserInfoAPI(props.userInfo.userId, userInfo.value);
    emit('close', true);
  } catch (error) {
    // 处理错误：区分“用户取消”和“其他错误”
    if (error.message === '用户取消操作') {
      // 用户点击“取消”：根据需求决定是否关闭弹窗
      // 如果你希望取消时不关闭弹窗，就删除这行
      emit('close', false);
      // 不抛出错误，避免全局捕获
      return;
    }
    // 其他错误（如接口失败）：关闭弹窗并抛出错误
    emit('close', false);
    console.error('修改失败', error);
  }
}
const isImageCropperShow = ref(false);
// 图片对象
const imageFile = ref(null);
// 头像预览URL
const avatarPreviewUrl = ref('');
// 裁剪后的头像URL
const avatarCroppedUrl = ref('');
function handleAvatarChange(e) {
  // 检查是否选择了文件
  if (!e.target.files.length) {
    console.log('请选择图片');
    return;
  }
  const file = e.target.files[0];
  // 2. 验证文件类型（仅允许图片）
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    console.log('请选择图片格式文件(jpg、png等)');
    e.target.value = ''; // 清空选择，避免重复触发
    return;
  }

  // 3. 验证文件大小（例如限制 5MB 以内）
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    console.log('图片大小不能超过5MB');
    e.target.value = '';
    return;
  }
  const imageUrl = URL.createObjectURL(file);
  imageFile.value = file; // 原始文件（后续裁剪后需上传）
  avatarPreviewUrl.value = imageUrl; // 临时预览URL
  // 6. 显示裁剪组件
  isImageCropperShow.value = true;

  // 清空input值，避免重复选择同一文件时不触发change事件
  e.target.value = '';
}
// 确认裁剪
function handleConfirm(croppedUrl) {
  console.log('croppedUrl', croppedUrl);
  // 1. 关闭裁剪组件
  isImageCropperShow.value = false;
  // 2. 更新头像预览URL（可选）
  avatarCroppedUrl.value = croppedUrl;
  // 3. 更新头像图片
  avatarImg.value.src = croppedUrl;
}
// 上传头像
async function uploadAvatar() {
  try {
    await uploadAvatarAPI(props.userInfo.userId, {
      fieldName: avatarCroppedUrl.value
    });
    console.log('头像上传成功');
  } catch (error) {
    console.error('头像上传失败', error);
  }
}
// 关闭裁剪组件
function handleClose() {
  isImageCropperShow.value = false;
}
</script>